package com.aikon.wht.concurrent;

public class DeadLock {

	private String objId;

	private DeadLock(String id) {
		objId = id;
	}

	public synchronized void checkOther(DeadLock other) {
		print("Entering checkOther");
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		print("In checkOther - about to invoke other.action");
		other.action();
		print("leaving checkOther");
	}

	private synchronized void action() {
		print("Entering action");
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		print("Leaving action");

	}

	private void print(String string) {

		System.out.println(Thread.currentThread().getName() + "objId:" + objId + string);
	}

	public static void main(String[] args) {
		final DeadLock obj1 = new DeadLock("obj1");
		final DeadLock obj2 = new DeadLock("obj2");
		Runnable runA = new Runnable() {

			public void run() {

				obj1.checkOther(obj2);
			}
		};

		new Thread(runA, "ThreadA").start();
		
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		Runnable runB = new Runnable(){

			public void run() {
				obj2.checkOther(obj1);
			}
			
		};
		
		new Thread(runB,"ThreadB").start();
		
		

	}

}
